from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    """
    Extends the default User model to include additional profile information.
    """
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    full_name = models.CharField(max_length=100, blank=True, verbose_name="Full Name")
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, verbose_name="Avatar")
    nfc_card_id = models.CharField(max_length=50, unique=True, null=True, blank=True, help_text="Unique ID of the user's NFC card")

    def __str__(self):
        return f"{self.user.username}'s Profile"

@receiver(post_save, sender=User)
def create_or_update_user_profile(sender, instance, created, **kwargs):
    """
    Automatically create or update a Profile instance when a User is created or updated.
    This single signal handler prevents duplicate Profile creation.
    """
    if created:
        # Only create if it doesn't exist
        Profile.objects.get_or_create(user=instance)
    else:
        # For existing users, ensure they have a profile
        if hasattr(instance, 'profile'):
            instance.profile.save()
        else:
            # Create profile if it doesn't exist (edge case)
            Profile.objects.get_or_create(user=instance)
